package service

import (
	"context"
	"fx_swift_schedule/api"
	"fx_swift_schedule/internal/model"
	"fx_swift_schedule/pkg/code"
	"fx_swift_schedule/pkg/global"
	"fx_swift_schedule/pkg/internalerrors"
	"fx_swift_schedule/pkg/logger"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"strconv"
)

type IComplyCallBackSrv interface {
	CustomerCompletedCallBack(ctx context.Context, req *api.CustomerCallBackReq) error
}
type complyCallBackSrv struct {
}

func NewComplyCallBackSrv() IComplyCallBackSrv {
	return &complyCallBackSrv{}
}

// KYC completed状态回调
func (c complyCallBackSrv) CustomerCompletedCallBack(ctx context.Context, req *api.CustomerCallBackReq) error {
	g.Dump("回调参数打印：", req)
	var (
		err         error
		customerObj *model.ForexOnboardingCustomer
		//workflowResult     string
		customerIdentifier string
		customerStatus     string
		overallValue       string
		overallLevel       string
		screeningResult    string
		//errorMessage       string
	)
	//reqStr, _ := json.Marshal(req)
	//workflowResult = string(reqStr)
	customerIdentifier = req.StepDetails.CustomerCreation.StepOutput.CustomerIdentifier
	customerStatus = req.Status
	overallValue = strconv.Itoa(req.StepDetails.InitialRiskScoring.StepOutput.OverallValue)
	overallLevel = req.StepDetails.InitialRiskScoring.StepOutput.OverallLevel
	screeningResult = req.StepDetails.CustomerScreening.StepOutput.ScreeningResult
	//errorMessage = req.StepDetails.CustomerCreation.ErrorMessage

	if err = global.GFDB.Schema("forex").Model("forex_onboarding_customer").
		Where("workflow_instance_identifier=?", req.WorkflowInstanceIdentifier).Scan(&customerObj); err != nil {
		logger.SugarLogger.Error(err)
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if customerObj != nil {
		db := g.DB().Schema("forex")
		err = db.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
			if _, err = tx.Model("forex_onboarding_customer").Data(g.Map{"customer_status": customerStatus,
				"customer_identifier": customerIdentifier, "overall_value": overallValue, "overall_level": overallLevel, "screening_result": screeningResult}).
				Where("workflow_instance_identifier=?", req.WorkflowInstanceIdentifier).Update(); err != nil {
				logger.SugarLogger.Error(err)
				return internalerrors.New(code.ErrUnknown, "更新异常")
			}
			return err
		})
	}
	return nil
}
